﻿using System.Data;
using LoadIn.Maps.Bing.Models;
using Orchard.ContentManagement;
using Orchard.ContentManagement.MetaData;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;
using Orchard.Environment;
using Orchard.Environment.Extensions;
using Orchard.Localization;
using Orchard.UI.Notify;

namespace LoadIn.Maps.Bing
{
    [OrchardFeature("LoadIn.Maps.Bing")]
    public class BingMapsMigrations : DataMigrationImpl
    {
        private readonly Work<IContentManager> _content;
        private readonly Work<INotifier> _notifier;

        public Localizer T;

        public BingMapsMigrations(Work<IContentManager> content, Work<INotifier> notifier)
        {
            _content = content;
            _notifier = notifier;
            T = NullLocalizer.Instance;
        }

        public int Create()
        {
            // create settings table
            try
            {
                SchemaBuilder.CreateTable(
                    "BingMapsSettingsPartRecord",
                    table => table
                                 .ContentPartRecord()
                                 .Column<string>("ApiKey")
                                 .Column<string>("Mode")
                    );
            }
            catch
            {
                _notifier.Value.Warning(T("Skipping BingMapsSettingsPartRecord table creation. It already exists."));
            }

            // create bing maps part table
            try
            {
                SchemaBuilder.CreateTable("BingMapsPartRecord",
                    table => table
                        .ContentPartRecord()
                    .Column("Latitude", DbType.String)
                    .Column("Longitude", DbType.String)
                    .Column("Width", DbType.Int32)
                    .Column("Height", DbType.Int32)
                    .Column("Zoom", DbType.Int32)
                    .Column("Mode", DbType.String)
                    .Column("PinIcon", DbType.String)
                    .Column("PinText", DbType.String)
                    );
            }
            catch
            {
                _notifier.Value.Warning(T("Skipping BingMapsPartRecord table creation. It already exists."));
            }

            ContentDefinitionManager.AlterPartDefinition(typeof(BingMapsPart).Name,
                                 cfg => cfg.Attachable());

            return 1;
        }

        public int UpdateFrom1()
        {
            // Create a new widget content type with our Bing map
            ContentDefinitionManager.AlterTypeDefinition("BingMapsWidget", cfg => cfg
                .WithPart("BingMapsPart")
                .WithPart("WidgetPart")
                .WithPart("CommonPart")
                .WithSetting("Stereotype", "Widget"));

            return 2;
        }
    }
}